package cn.changeforyou.analyzer.xmlparse.mybatis.reader;

import cn.changeforyou.analyzer.combine.orm.XmlCodeType;
import cn.changeforyou.analyzer.xmlparse.mybatis.model.ResultMapLabel;
import cn.changeforyou.analyzer.xmlparse.mybatis.model.ResultMapLabel.ResultTag;
import cn.changeforyou.analyzer.xmlparse.mybatis.reader.AbstractXmlLabelReaderWriter;
import java.util.ArrayList;
import java.util.List;
import org.dom4j.Node;
import org.dom4j.tree.DefaultElement;

public abstract class ResultMapLabelReader extends AbstractXmlLabelReaderWriter<ResultMapLabel> {
	
	@Override
	protected List<ResultMapLabel> read(List<Node> nodes) {
		List<ResultMapLabel> resultMapLabels = new ArrayList<>();
		for (Node node : nodes) {
			if (node instanceof DefaultElement) {
				ResultMapLabel resultMapLabel = new ResultMapLabel();
				resultMapLabels.add(resultMapLabel);
				DefaultElement element = (DefaultElement) node;
				resultMapLabel.setNode(element);
				
				String id = element.attribute("id").getStringValue();
				String type = element.attribute("type").getStringValue();
				resultMapLabel.setId(XmlCodeType.valueOf(id));
				resultMapLabel.setType(type);
				List<ResultTag> results = new ArrayList<>();
				resultMapLabel.setResultTags(results);
				
				List<Node> resultNodes = element.content();
				for (Node resultNode : resultNodes) {
					if (resultNode instanceof DefaultElement) {
						DefaultElement result = (DefaultElement) resultNode;
						if (!result.getName().equals("result")) {
							continue;
						}
						ResultTag resultTag = new ResultTag(resultMapLabel);
						results.add(resultTag);
						
						String column = result.attribute("column").getStringValue();
						String property = result.attribute("property").getStringValue();
						resultTag.setColumn(column);
						resultTag.setProperty(property);
						resultTag.setNode(result);
					}
				}
			}
		}
		return resultMapLabels;
	}
	
	@Override
	protected String getXpath() {
		return "/mapper/resultMap]";
	}
}
